package cn.ryh.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import static java.lang.Thread.sleep;

/**
 * 群聊客户端
 *
 * @author Raoyh
 * @Description
 * @create 2022-09-13 10:42
 */
public class Client {
    public static void main(String[] args) {
        //启动我们客户端
        Client chatClient = new Client();
        //启动一个线程,每个 3 秒，读取从服务器发送数据
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    chatClient.readInfo();
                    try {
                        sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        while (true) {
            try {
                sleep(3000);
                chatClient.sendInfo("测试");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 定义属性
     */
    private final String ip = "127.0.0.1";
    private static final int PORT = 6667;
    private final Selector selector;
    private final SocketChannel socketChannel;
    private String name;

    public Client() {
        try {
            selector = Selector.open();
            // 连接服务器
            socketChannel = SocketChannel.open(new InetSocketAddress(ip, PORT));
            // 设置为非阻塞
            socketChannel.configureBlocking(false);
            // 将socketChannel注册到 selector
            socketChannel.register(selector, SelectionKey.OP_READ);
            name = socketChannel.getLocalAddress().toString().substring(10);
            System.out.println(name + " is ok .....");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 向服务器发送消息
     *
     * @param info
     */
    public void sendInfo(String info) {
        info = name + " 说：" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取从服务器端回复的消息
     */
    public void readInfo() {
        try {
            int readChannels = selector.select();
            //有可以用的通道
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        //得到相关的通道
                        ByteBuffer buffer;
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个 Buffer
                        buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);

                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的 selectionKey,防止重复操作
            } else {
                //System.out.println("没有可以用的通道...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
